"""
统一服务启动器
集成MCP服务、API网关、数据同步服务和调度器服务
"""

import asyncio
import logging
import signal
import sys
from contextlib import asynccontextmanager
from typing import Dict, Any, Optional
import uvicorn
from fastapi import FastAPI

from .core.config import config
from .core.database import db_manager, init_database
from .core.cache import cache_manager
from .data_sync_service import data_sync_service, init_data_sync_service
from .api_gateway import FinancialDataAPIGateway
from .scheduler_service import TaskScheduler

# 配置日志
logging.basicConfig(
    level=getattr(logging, config.monitoring.log_level.upper()),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout),
        logging.FileHandler('financial_mcp_server.log')
    ]
)

logger = logging.getLogger(__name__)


class FinancialMCPServer:
    """金融MCP服务器主类"""
    
    def __init__(self):
        self.logger = logging.getLogger(f"{__name__}.FinancialMCPServer")
        self.api_gateway: Optional[FinancialDataAPIGateway] = None
        self.task_scheduler: Optional[TaskScheduler] = None
        self.app: Optional[FastAPI] = None
        self._shutdown_event = asyncio.Event()
        self._services_started = False
    
    async def initialize(self):
        """初始化所有服务"""
        try:
            self.logger.info("开始初始化金融MCP服务器...")
            
            # 1. 初始化数据库
            self.logger.info("初始化数据库...")
            await init_database()
            
            # 2. 初始化缓存
            self.logger.info("初始化缓存系统...")
            await cache_manager.initialize()
            
            # 3. 初始化数据同步服务
            self.logger.info("初始化数据同步服务...")
            await init_data_sync_service()
            
            # 4. 初始化API网关
            self.logger.info("初始化API网关...")
            self.api_gateway = FinancialDataAPIGateway()
            # API网关不需要单独的initialize方法
            
            # 5. 初始化任务调度器
            self.logger.info("初始化任务调度器...")
            self.task_scheduler = TaskScheduler(config)
            await self.task_scheduler.initialize()
            
            # 6. 创建FastAPI应用
            self.app = await self._create_app()
            
            self.logger.info("金融MCP服务器初始化完成")
            
        except Exception as e:
            self.logger.error(f"服务器初始化失败: {e}")
            raise
    
    async def _create_app(self) -> FastAPI:
        """创建FastAPI应用"""
        @asynccontextmanager
        async def lifespan(app: FastAPI):
            """应用生命周期管理"""
            try:
                # 启动服务
                await self.start_services()
                yield
            finally:
                # 关闭服务
                await self.stop_services()
        
        # 创建主应用
        app = FastAPI(
            title="金融数据MCP服务器",
            description="基于MCP协议的企业级金融数据服务平台",
            version="1.0.0",
            lifespan=lifespan
        )
        
        # 挂载API网关
        if self.api_gateway and self.api_gateway.app:
            app.mount("/api", self.api_gateway.app)
        
        # 添加根路径健康检查
        @app.get("/")
        async def root():
            return {
                "service": "金融数据MCP服务器",
                "version": "1.0.0",
                "status": "running",
                "components": {
                    "mcp_service": True,
                    "api_gateway": self.api_gateway is not None,
                    "data_sync": data_sync_service._initialized if data_sync_service else False,
                    "task_scheduler": self.task_scheduler.running if self.task_scheduler else False
                }
            }
        
        # 添加系统状态接口
        @app.get("/status")
        async def system_status():
            return await self.get_system_status()
        
        # 添加服务控制接口
        @app.post("/control/restart")
        async def restart_services():
            """重启所有服务"""
            try:
                await self.restart_services()
                return {"status": "success", "message": "服务重启成功"}
            except Exception as e:
                return {"status": "error", "message": f"服务重启失败: {e}"}
        
        @app.post("/control/stop")
        async def stop_server():
            """停止服务器"""
            try:
                self._shutdown_event.set()
                return {"status": "success", "message": "服务器正在关闭"}
            except Exception as e:
                return {"status": "error", "message": f"服务器关闭失败: {e}"}
        
        return app
    
    async def start_services(self):
        """启动所有服务"""
        if self._services_started:
            return
        
        try:
            self.logger.info("启动所有服务...")
            
            # 启动数据同步服务
            if data_sync_service:
                await data_sync_service.start()
                self.logger.info("数据同步服务已启动")
            
            # 启动任务调度器
            if self.task_scheduler:
                await self.task_scheduler.start()
                self.logger.info("任务调度器已启动")
            
            self._services_started = True
            self.logger.info("所有服务启动完成")
            
        except Exception as e:
            self.logger.error(f"服务启动失败: {e}")
            raise
    
    async def stop_services(self):
        """停止所有服务"""
        if not self._services_started:
            return
        
        try:
            self.logger.info("停止所有服务...")
            
            # 停止任务调度器
            if self.task_scheduler:
                await self.task_scheduler.stop()
                self.logger.info("任务调度器已停止")
            
            # 停止数据同步服务
            if data_sync_service:
                await data_sync_service.stop()
                self.logger.info("数据同步服务已停止")
            
            # 关闭缓存连接
            if cache_manager:
                await cache_manager.close()
                self.logger.info("缓存连接已关闭")
            
            # 关闭数据库连接
            if db_manager:
                await db_manager.close()
                self.logger.info("数据库连接已关闭")
            
            self._services_started = False
            self.logger.info("所有服务停止完成")
            
        except Exception as e:
            self.logger.error(f"服务停止失败: {e}")
    
    async def restart_services(self):
        """重启所有服务"""
        self.logger.info("重启所有服务...")
        await self.stop_services()
        await asyncio.sleep(2)  # 等待服务完全停止
        await self.start_services()
        self.logger.info("服务重启完成")
    
    async def get_system_status(self) -> Dict[str, Any]:
        """获取系统状态"""
        status = {
            "server": {
                "status": "running" if self._services_started else "stopped",
                "uptime": "N/A"  # 可以添加运行时间统计
            },
            "services": {},
            "resources": {
                "database": False,
                "cache": False,
                "memory_usage": "N/A",
                "cpu_usage": "N/A"
            }
        }
        
        try:
            # 检查数据同步服务状态
            if data_sync_service:
                sync_status = await data_sync_service.get_sync_status()
                status["services"]["data_sync"] = sync_status
            
            # 检查任务调度器状态
            if self.task_scheduler:
                scheduler_status = {
                    "running": self.task_scheduler.running,
                    "tasks_count": len(self.task_scheduler.tasks),
                    "active_executions": len([e for e in self.task_scheduler.executions.values() if e.status.value == "running"])
                }
                status["services"]["task_scheduler"] = scheduler_status
            
            # 检查数据库连接
            try:
                async with db_manager.get_session() as session:
                    from sqlalchemy import text
                    await session.execute(text("SELECT 1"))
                status["resources"]["database"] = True
            except:
                status["resources"]["database"] = False
            
            # 检查缓存连接
            try:
                cache = cache_manager.get_cache("system")
                await cache.set("health_check", "ok", ttl=60)
                result = await cache.get("health_check")
                status["resources"]["cache"] = (result == "ok")
            except:
                status["resources"]["cache"] = False
            
        except Exception as e:
            self.logger.error(f"获取系统状态失败: {e}")
        
        return status
    
    async def run(self, host: str = "0.0.0.0", port: int = 8000):
        """运行服务器"""
        try:
            # 初始化服务器
            await self.initialize()
            
            # 设置信号处理
            def signal_handler(signum, frame):
                self.logger.info(f"接收到信号 {signum}，准备关闭服务器...")
                self._shutdown_event.set()
            
            signal.signal(signal.SIGINT, signal_handler)
            signal.signal(signal.SIGTERM, signal_handler)
            
            # 启动HTTP服务器
            if not self.app:
                raise RuntimeError("应用未初始化")
            
            config_uvicorn = uvicorn.Config(
                app=self.app,
                host=host,
                port=port,
                log_level=config.monitoring.log_level.lower(),
                access_log=True
            )
            
            server = uvicorn.Server(config_uvicorn)
            
            self.logger.info(f"金融MCP服务器启动在 http://{host}:{port}")
            self.logger.info("API文档地址: http://localhost:8000/docs")
            self.logger.info("按 Ctrl+C 停止服务器")
            
            # 启动服务器任务
            server_task = asyncio.create_task(server.serve())
            
            # 等待关闭信号
            shutdown_task = asyncio.create_task(self._shutdown_event.wait())
            
            # 等待任一任务完成
            done, pending = await asyncio.wait(
                [server_task, shutdown_task],
                return_when=asyncio.FIRST_COMPLETED
            )
            
            # 取消未完成的任务
            for task in pending:
                task.cancel()
                try:
                    await task
                except asyncio.CancelledError:
                    pass
            
            # 如果是关闭信号触发，停止服务器
            if shutdown_task in done:
                self.logger.info("正在关闭服务器...")
                server.should_exit = True
                await server_task
            
        except Exception as e:
            self.logger.error(f"服务器运行失败: {e}")
            raise
        finally:
            # 确保服务被正确关闭
            await self.stop_services()


# 全局服务器实例
server = FinancialMCPServer()


async def main():
    """主函数"""
    try:
        # 从配置中获取服务器参数
        host = getattr(config.mcp, 'host', '0.0.0.0')
        port = getattr(config.mcp, 'port', 8000)
        
        await server.run(host=host, port=port)
        
    except KeyboardInterrupt:
        logger.info("接收到键盘中断信号")
    except Exception as e:
        logger.error(f"服务器运行异常: {e}")
        sys.exit(1)
    finally:
        logger.info("服务器已关闭")


if __name__ == "__main__":
    # 运行服务器
    asyncio.run(main())